//
//  ImageViewController.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/5/7.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import Kingfisher

class ImageViewController: UIViewController , UIScrollViewDelegate{

    static let VCID = "ImageViewController"
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var imageView: UIImageView!
    
    var imageUrl = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.imageView.layer.borderColor = UIColor.black.cgColor
//        self.imageView.layer.borderWidth = 1
        self.imageView.contentMode = .scaleAspectFit
        self.imageView.kf.setImage(with:URL(string:imageUrl))
        self.scrollView.maximumZoomScale = 2
        self.scrollView.backgroundColor = UIColor.white
        self.scrollView.delegate = self
        
        scrollView.contentInset = UIEdgeInsets.init(top: -64, left: 0, bottom: 0, right: 0)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(ImageViewController.zoomAction(_:)))
        tap.numberOfTapsRequired = 2
        self.scrollView.addGestureRecognizer(tap)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // MARK: - Navigation
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imageView;
    }
    
    // 让UIImageView在UIScrollView缩放后居中显示
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        
        var offsetX:CGFloat = 0
        var offsetY:CGFloat = 0
        let k:CGFloat = 0.5
        if scrollView.bounds.size.width > scrollView.contentSize.width {
            offsetX = (scrollView.bounds.size.width - scrollView.contentSize.width) * k
        }
        
        if scrollView.bounds.size.height > scrollView.contentSize.height {
            offsetY = (scrollView.bounds.size.height - scrollView.contentSize.height) * k
        }
        
        self.imageView.center = CGPoint.init(x:scrollView.contentSize.width * k + offsetX,
                                             y:scrollView.contentSize.height * k + offsetY);

    }
    
    @objc func zoomAction(_ ges:UITapGestureRecognizer){
        let loc = ges.location(in: ges.view)
        if (self.scrollView.zoomScale != 1) {
            self.scrollView.setZoomScale(1, animated: true)
            return;
        }
        var frame = self.scrollView.bounds;
        frame.size.width /= self.scrollView.maximumZoomScale;
        frame.size.height /= self.scrollView.maximumZoomScale;
        frame.origin.x = loc.x - frame.size.width/2 ;
        frame.origin.y = loc.y - frame.size.height/2 ;
        self.scrollView.zoom(to: frame, animated: true)
    }

}
